#pragma once
#include "DXAMLCommon.h"
#include "CImageSource.h"
#include "CTiledSurface.h"
#include "xchainedmap.h"

class CSurfaceImageSource :
	public CImageSource
{

protected: 
	static const XINT32 sc_MinStandAloneSize;
	CSurfaceImageSource(CCoreServices * pCore);
public: 
	virtual ~CSurfaceImageSource();
	HRESULT Create(XINT32 width, XINT32 height, XBOOL isOpaque);
	static HRESULT Create(CDependencyObject * * ppObject, CREATEPARAMETERS * pCreate);
	virtual XUINT32 GetTypeIndex() const;
	HRESULT SetDevice(struct IUnknown * pDevice);
	HRESULT BeginDraw(struct XRECT_WH updateRect, struct IPALSurfaceUpdate * * ppSurfaceUpdate);
	HRESULT EndDraw();
	virtual HRESULT EnsureAndUpdateHardwareResources(HWTextureManager * pTextureManager, CRenderTarget * pRenderTarget, SurfaceCache * pSurfaceCache);
	virtual HRESULT HandleLostResources(SurfaceCache * pSurfaceCache, XBOOL * pWasDeviceLost);
	void CleanUpAfterRenderThreadFailure();
	virtual XBOOL HasDimensions();
protected: 
	XBOOL IsDrawing();
	HRESULT ProcessPendingUpdates(HWTextureManager * pTextureManager, CRenderTarget * pRenderTarget);
	virtual HRESULT PreUpdateVirtual(const struct XRECT_WH * pUpdateRect);
	virtual HRESULT EnsureTiles(HWTextureManager * pTextureManager);
	HRESULT AddTile(struct XPOINT origin, struct XSIZE size, XUINT64 timestamp, XBOOL initializeToTransparent);
	XUINT32 GetTileCount();
	xchainedmap<XPOINT,CTiledSurface::Tile *>::const_iterator BeginTiles();
	xchainedmap<XPOINT,CTiledSurface::Tile *>::const_iterator EndTiles();
	XUINT32 GetMaxTextureDimension();
	virtual XBOOL SupportsFlipping();
	virtual XBOOL UsePermanentAtlas();
	virtual XBOOL IsTileCompletelyFilled(const struct CTiledSurface::Tile * pTile);
	virtual void SetInteropUsage();
private: 
	HRESULT SubmitFlip(HWTextureManager * pTextureManager, struct IPALSurfaceUpdate * pSurfaceUpdate, struct CTiledSurface::Tile * pTile);
	HRESULT SubmitOneUpdate(HWTextureManager * pTextureManager, struct IPALSurfaceUpdate * pSurfaceUpdate);
	XBOOL ShouldFlip(struct IPALSurfaceUpdate * pSurfaceUpdate, struct IPALOptimizedGraphicsDevice * pGraphicsDevice, struct CTiledSurface::Tile * * ppTile);
	struct IUnknown * m_pDevice;
	struct IPALSurfaceUpdatePool * m_pSurfaceUpdatePool;
	struct IPALSurfaceUpdate * m_pCurrentUpdate;
	xvector<xref_ptr<IPALSurfaceUpdate> > m_pendingUpdates;

	XUINT32 m_onGlobalSISList:1;


};